package com.owen.controller;

import com.alibaba.fastjson2.JSON;
import com.owen.pojo.User;
import com.owen.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    private UserServer userServer;

    @ResponseBody
    @RequestMapping(value = "userLogin",method = RequestMethod.POST)
    public String login(User user, HttpSession session) {
        Map<String ,Object> res = new HashMap<>();
        if (Optional.ofNullable(user).isPresent()){
            // 获取用户名
            String username = user.getUsername();
            // 获取密码
            String password = user.getPassword();

            User login = userServer.login(username, password);
            if(Optional.ofNullable(login).isPresent() && login.getUserLock() == 1){
                res.put("code", "201");
                res.put("msg", "登录失败");
            } else if (Optional.ofNullable(login).isPresent()) {
                session.setAttribute("login", login);
                res.put("code", "200");
                res.put("msg", "登录成功");
//                VoiceUtil.textToSpeech(login.getUsername() + "登录成功");
            }else {
                res.put("code", "201");
                res.put("msg", "登录失败，账号或密码错误。");
            }
        }else {
            res.put("code", "201");
            res.put("msg", "信息不完整");
        }

        String s = JSON.toJSONString(res);
        return s;
    }

}
